<template>
  <div class="miwenBox">
    <div class="handle leftHandle" @click="clickLeft">
      <a-icon class="close-icon" type="right" title="展开" />
    </div>
    <div class="handle rightHandle" v-show="rightVisible" @click="clickRight">
      <a-icon class="close-icon" type="left" title="展开" />
    </div>
    <div class="map" id="map"></div>
    <!--@change="onSearch"-->
    <div style="position: absolute;left: 50%;top: 50%;margin-top:-16px;margin-left:-32px;">
      <a-spin :spinning="searchLoading" tip="" size="large" />
    </div>
    <div v-show="isLoading" class="loading"><a-icon type="loading" />查询中...</div>
    <MiwenListDrawer :visible="isMiwenListShow" @close="closeMiwenListDrawer" @clickRow="onClickRow" />
    <DetailModal1 @close="closeDetail1" ref="detailModal1" v-show="isDetail1Show" />
    <DetailModal2
      @close="closeDetail2"
      ref="detailModal2"
      v-show="isDetail2Show"
      @on-task-details-drawer="drawTaskDetailsDrawer"
    />
    <DetailModal3
      @close="closeDetail3"
      ref="detailModal3"
      v-show="isDetail3Show"
      @on-task-details-drawer="drawTaskDetailsDrawer"
    />
  </div>
</template>

<script>
import MiwenListDrawer from './components/miwen_list_drawer'
import DetailModal1 from './components/detailModal1'
import DetailModal2 from './components/detailModal2'
import DetailModal3 from './components/detailModal3'
import { testFloat } from '@/libs/tools'
import config from '@/defaultSettings'

function ComplexCustomOverlay(point, html) {
  this._point = point
  this._html = html
}
ComplexCustomOverlay.prototype = new BMap.Overlay()
ComplexCustomOverlay.prototype.initialize = function(map) {
  this._map = map
  var div = (this._div = document.createElement('div'))
  div.setAttribute('class', 'marker')
  div.innerHTML = this._html

  this._map.getPanes().labelPane.appendChild(div)
  return div
}
ComplexCustomOverlay.prototype.draw = function() {
  var map = this._map
  var pixel = map.pointToOverlayPixel(this._point)
  this._div.style.left = pixel.x + 'px'
  this._div.style.top = pixel.y + 'px'
}

export default {
  components: {
    MiwenListDrawer,
    DetailModal1,
    DetailModal2,
    DetailModal3
  },
  data() {
    return {
      taskId: this.$route.params.id, // 案事件管理_案事件详情_任务详情接口传参
      map: null,
      newPoint: null,
      isSend: false,
      isLoading: false,
      MarkerList: '',
      searchLoading: false,
      mncMap: {
        '00': 'yidong',
        '01': 'liantong',
        '03': 'dianxin'
      },
      sanjiaoBox: {
        longitude: '',
        latitude: '',
        text: '',
        left: 0,
        top: 0
      },
      taskDetail: [], // 案事件详情
      isMiwenListShow: true,
      isDetail1Show: false,
      isDetail2Show: false,
      isDetail3Show: false,
      rightVisible: false,
      modelType: '',
      phone: ''
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.drawMap()
    })
    let mapHeight = window.innerHeight
    document.getElementById('map').style.height = `${mapHeight}px`
    window.onresize = function() {
      let winHeight = window.innerHeight
      document.getElementById('map').style.height = `${winHeight}px`
    }
  },
  methods: {
    clickRight() {
      this.rightVisible = false
      // this.isDetailModalShow = true
      if (this.modelType == 1) {
        this.isDetail1Show = true
      }
      if (this.modelType == 2) {
        this.isDetail2Show = true
      }
      if (this.modelType == 3) {
        this.isDetail3Show = true
      }
    },
    closeMiwenListDrawer() {
      this.isMiwenListShow = false
    },
    closeDetail1() {
      this.isDetail1Show = false
      this.rightVisible = true
    },
    closeDetail2() {
      this.isDetail2Show = false
      this.rightVisible = true
    },
    closeDetail3() {
      this.isDetail3Show = false
      this.rightVisible = true
    },
    onClickRow(row) {
      // 关闭查询轨迹弹窗
      this.map.clearOverlays()
      this.map.removeEventListener('click', this.getMapPoint)
      this.isDetail1Show = false
      this.isDetail2Show = false
      this.isDetail3Show = false
      this.rightVisible = false
      this.modelType = row.modelType
      this.phone = row.phone
      if (row.modelType == 1) {
        //异常出入岛人群挖掘
        this.isDetail1Show = true
        this.$refs.detailModal1.show(row)
      }
      if (row.modelType == 2) {
        //可疑船舶与人员关系挖掘
        this.isDetail2Show = true
        this.$refs.detailModal2.show(row)
      }
      if (row.modelType == 3) {
        //消费行为异常人员挖掘
        this.isDetail3Show = true
        this.$refs.detailModal3.show(row)
      }
    },
    onDetail(index) {
      console.log('index：' + index)
      this.isMiwenListShow = false
      this.isDetail1Show = false
    },
    onPY() {
      this.isMiwenListShow = true
      this.isDetail1Show = true
    },
    onTransfer(id) {
      console.log('id')
      console.log(id)
      this.$refs.transModalId.show(id)
    },
    lightIcon(className) {
      if (document.getElementsByClassName(className).length > 0) {
        document.getElementsByClassName(className)[0].style.backgroundColor = 'blue'
        setTimeout(() => {
          document.getElementsByClassName(className)[0].style.backgroundColor = '#0000ff00'
        }, 1000)
      }
    },
    goBack() {
      this.$router.back(-1)
    },
    clickLeft() {
      this.isMiwenListShow = true
    },
    drawMap() {
      this.map = new BMap.Map('map', { maxZoom: 18 })
      // this.map.centerAndZoom(new BMap.Point(125.35, 43.88), 12)
      this.map.centerAndZoom(new BMap.Point(config.initLng, config.initLat), 12)
      this.map.enableScrollWheelZoom()
    },
    addLine(data, type) {
      const colors = {
        red: '#d91f1b',
        blue: '#009dd9',
        // blue: "#2F98F4",
        green: '#48bb00',
        violet: '#762bd0',
        deongaree: '#1921b3',
        orange: 'orange'
      }
      let line = []
      data.forEach((item, index) => {
        line.push(new BMap.Point(item.longitude, item.latitude))
      })
      var polyline = new BMap.Polyline(line, {
        strokeColor: colors[type],
        strokeWeight: 2.5,
        strokeOpacity: 0.8
      }) // 创建折线
      this.map.addOverlay(polyline) // 增加折线
    },
    dateFormat(value) {
      var date = new Date(value)
      let Y = date.getFullYear() + '-'
      let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
      let D = date.getDate() + ' '
      let h = date.getHours() > 9 ? date.getHours() + ':' : '0' + date.getHours() + ':'
      let m = date.getMinutes() > 9 ? date.getMinutes() + ':' : '0' + date.getMinutes() + ':'
      let s = date.getSeconds() > 9 ? date.getSeconds() + ':' : '0' + date.getSeconds()
      return Y + M + D + h + m + s
    },
    getText(text) {
      if (!text) return ''
      let l = text.split('\n')
      let s = ''
      l.forEach(v => {
        s += `<p>${v}</p>`
      })
      return s
    },
    addMarker(data, type) {
      // console.log(data)
      // console.log(type)
      // debugger
      data.forEach((item, index) => {
        const mnc = this.mncMap[item.mnc]
        const point = new BMap.Point(item.longitude, item.latitude)
        // const html = `<span class="sign ${item.flag ? 'orange' : type}" style="background-image: url("../../assets/images/${mnc}_${type}.png")">${index + 1}</span>`
        let html = `<span class="index${index} sign${mnc ? '' : ' red'} ${
          item.elapsedEndTime ? type : !item.flag ? mnc + '_black' : mnc + '_' + type
        }"></span>`
        if (item.repeatLine) {
          html = `<span class="saojiao"></span>`
        }
        // console.log(html)
        // html += item.repeatLine ? `<span class="saojiao" longitude=${item.longitude} latitude=${item.latitude} text='${item.text}'></span>` : ''
        const myCompOverlay = new ComplexCustomOverlay(point, html)
        let marker = new BMap.Marker(point)
        this.map.addOverlay(marker)
        this.map.addOverlay(myCompOverlay)
        // var label = new BMap.Label('<div style="position: relative;border: none !important;z-index:99999;background: rgba(0, 0, 0, 0.65);color: #fff;font-size: 14px;padding: 10px;line-height: 25px"><p>' + '参考点[' + (index + 1) + ']</p><p>' + '经度:' + item.longitude + '</p><p>' + '纬度:' + item.latitude + this.getText(item.text) + '</div>', {
        //   offset: new BMap.Size(20, -110){}
        let label

        label = new BMap.Label(
          '<div style="position: relative;border: none !important;z-index:99999;background: rgba(0, 0, 0, 0.65);color: #fff;font-size: 14px;padding: 10px;line-height: 25px">' +
            '手机号码：' +
            this.phone +
            '</p><p>' +
            '出现时间：' +
            item.appearTime +
            '</p><p>' +
            '经度：' +
            item.longitude +
            '</p><p>' +
            '纬度：' +
            item.latitude +
            '</p>',
          {
            offset: new BMap.Size(20, -110)
          }
        )

        marker.setLabel(label)
        // pointArray[i] = new BMap.Point(points[i].lon, points[i].lat);
        // 初始化不显示
        label.setStyle({
          display: 'none'
        })
        // 鼠标经过时
        marker.addEventListener('mouseover', function(e) {
          var label = this.getLabel()
          label.setStyle({
            display: 'block'
          })
        })
        // 鼠标离开时
        marker.addEventListener('mouseout', function(e) {
          var label = this.getLabel()
          label.setStyle({
            display: 'none'
          })
        })
      })
    },
    drawOverlay(data, type) {
      // debugger
      this.addLine(data, type)
      this.addMarker(data, type)
    },
    panTo(data, key) {
      const target = data.filter(item => key === item.key)[0]
      target && this.map.panTo(new BMap.Point(target.longitude, target.latitude))
    },
    // 判断输入的轨迹点是否完整
    setAccordList(data) {
      return data.filter(item => {
        return !testFloat(item.longitude) && !testFloat(item.latitude)
      })
    },
    // 获取地图某点坐标
    getMapPoint(e) {
      this.newPoint = {
        longitude: e.point.lng,
        latitude: e.point.lat
      }
    },
    // 新增查询轨迹成功后刷新任务列表
    getTaskList() {
      this.isSend = true
    },
    // 响应查询轨迹弹窗添加轨迹
    drawTaskAddDrawer(data, type, key) {
      const list = this.setAccordList(data)
      this.map.clearOverlays()
      this.drawOverlay(list, type)
      this.panTo(list, key)
      console.log(list, key)
    },
    getRepeatPointer(data) {
      let latitudeLongitude = []
      let isRepeatLaLoList = []
      data.forEach((item, index) => {
        if (index !== 0) {
          item.list.forEach(v => {
            let s = Number(v.latitude) + ',' + Number(v.longitude)
            if (latitudeLongitude.includes(s)) {
              isRepeatLaLoList.push(s)
              return
            }
            latitudeLongitude.push(s)
          })
        }
      })
      let l = []
      let repeatLineList = []
      data.forEach((item, index) => {
        if (index !== 0) {
          item.list.forEach((v, i2) => {
            v.listIndex = index
            let s = Number(v.latitude) + ',' + Number(v.longitude)
            if (isRepeatLaLoList.includes(s)) {
              let i = isRepeatLaLoList.indexOf(s)
              let time = new Date(v.arriveTime).Format('yyyy-MM-dd hh:mm:ss')
              v.isRepeat = true
              if (l.map(v1 => v1.index).includes(i)) {
                let y = l.map(v2 => v2.index).indexOf(i)
                // v.text = l[y].text + `\n【${i2 + 1}】${v.phone} ${index}号轨迹点 经过时间 ${time}`
                v.text = l[y].text + `\n ${v.phone} ${index}号轨迹点 经过时间 ${time}`
                v.index = l[y].index
                v.flag = v.flag || l[y].flag
                if (v.listIndex !== l[y].listIndex) {
                  v.repeatLine = true
                  repeatLineList.push(s)
                }
                l[y] = Object.assign({}, v)
                return
              }
              l.push({
                index: i,
                text: ` ${v.phone}  ${index}号轨迹点 经过时间 ${time}`,
                flag: v.flag,
                listIndex: v.listIndex
              })
              v.text = ` ${v.phone}  ${index}号轨迹点 经过时间 ${time}`
            }
          })
        }
      })
      data.forEach((item, index) => {
        if (index !== 0) {
          item.list.forEach(v => {
            let s = Number(v.latitude) + ',' + Number(v.longitude)
            if (repeatLineList.includes(s)) {
              v.repeatLine = true
            }
          })
        }
      })
    },
    drawTaskDetailsDrawer2_startLoad() {
      this.isLoading = true
    },
    // 响应任务查询结果弹窗添加标准轨迹
    drawTaskDetailsDrawer(data) {
      console.log('data')
      console.log(data)
      // debugger
      this.isLoading = false // 隐藏查询提示
      const colors = ['red', 'blue', 'green', 'violet', 'deongaree', 'orange']
      this.getRepeatPointer(data)
      this.map.clearOverlays()
      data.forEach((item, index) => {
        this.drawOverlay(item.list, colors[index])
        // 匹配到的轨迹标注序号
        if (index !== 0) {
          const point = new BMap.Point(item.list[0].longitude, item.list[0].latitude)
          const html = `<span class="tip ${colors[index]}">${item.key + 1}号轨迹</span>`
          const myCompOverlay = new ComplexCustomOverlay(point, html)
          this.map.addOverlay(myCompOverlay)
        }
      })
      this.panTo(data[data.length - 1].list, 0)
    },
    // 轨迹查询结果
    drawTaskDetailsDrawer1(data) {
      this.isLoading = false
      // 设置所有查询到的轨迹点数组
      this.$refs.piontDrawer.setPointData(data[0])
      //默认第一条轨迹点数据
      this.$refs.piontDrawer.show(true, 0)
    },
    //点击号码响应，显示对应的轨迹信息
    drawTaskDetailsDrawer2(index) {
      this.$refs.piontDrawer.show(true, index)
    }
  }
}
</script>

<style lang="less" scoped>
.miwenBox {
  position: relative;
  left: -10px;
  right: 0;
  top: -10px;
  bottom: 0;
  z-index: 800;
  // height: 650px;
  overflow: hidden;
  /deep/span.BMap_Marker {
    img {
      display: none !important;
    }
  }
  .ant-drawer-content-wrapper {
    height: 100% !important;
  }
  .breadcrumb-box {
    position: absolute;
    right: 20px;
    top: 7px;
    z-index: 10000;
  }
}
.map {
  .miwenBox;
  top: 0;
  transition: all 0.3s;
  &.offset-x-30 {
    left: 30%;
  }
}
.loading {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -100px);
  border-radius: 10px;
  width: 200px;
  line-height: 100px;
  text-align: center;
  font-size: 24px;
  color: #fff;
  background-color: rgba(0, 0, 0, 0.6);
  i {
    margin-right: 12px;
  }
}
.handle {
  position: absolute;
  display: inline-block;
  top: 0;
  z-index: 10;
  background: rgba(0, 0, 0, 0.6);
  height: 100%;
  cursor: pointer;
  transition: 0.5s;
  display: flex;
  flex-direction: column;
  justify-content: center;
  .close-icon {
    font-size: 20px;
    color: #fff;
  }
  &.leftHandle {
    left: 0;
  }
  &.rightHandle {
    right: 0;
  }
}
</style>
